<script setup lang='ts'>
  import { reactive, ref } from 'vue';
  import { roleApi, permissionApi } from '@/api/controller';
  import { ToastSuccess, Toastloading } from '@/utils/public';
  const $emit = defineEmits(['upadteList'])
  const treeRef = ref()
  const action = reactive({
    dialogFormVisible:false,
    permission:[] as any[],
    defaultCheckedKeys:[] as any[],
  })
  let form = {
    role_id:0,
    permission:[]
  }
  const handleSubmit = ()=> {
    form.permission = treeRef.value.getCheckedKeys();
    roleApi.updatePermission(form).then(() => {
      ToastSuccess('操作成功!')
      closeDialog()
      $emit('upadteList')
    }).catch(() => {
    })
  }
  const closeDialog = ()=> {
    action.dialogFormVisible = false
  }
  const openDialog = async(query:any ={})=> {
    const { id } = query;
    if(!id) return console.error('缺少id')
    form = {
      role_id:0,
      permission:[]
    }
    form.role_id = id;
    const loading = Toastloading();
    await getDefaultKeys(id)
    await getPermissions();
    loading.close()
    action.dialogFormVisible = true;
  }
  const getPermissions = ()=> {
    return permissionApi.getTree().then(response => {
      action.permission = response.data
    }).catch(() => {
    })
  }
  const getDefaultKeys = (id: any)=> {
    return roleApi.getRole(id).then(response => {
      action.defaultCheckedKeys = response.data
    })
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
    top="5vh"
    class="xm-dialog"
    v-model="action.dialogFormVisible"
    :close-on-click-modal="false"
    title="权限管理">
      <el-tree
        ref="treeRef"
        :data="action.permission"
        :expand-on-click-node="false"
        :default-checked-keys="action.defaultCheckedKeys"
        show-checkbox
        node-key="id"
        default-expand-all
        highlight-current/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang='scss' scoped>
  :deep(.xm-dialog) {
    .el-dialog__body {
      height: 65vh;
      overflow-y: auto;
    }
    .el-tree-node__children {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
    }
  }
</style>